package com.yzw.helloword;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * @Author: YangZhenWei
 * @PROJECT_NAME: nettyTeach
 * @DESCRIPTION:
 * @USER: root
 * @DATE: 2023/2/8 22:35
 **/
public class HandlerServerHello extends ChannelInboundHandlerAdapter {
    // 通道数组，让所有通道注册到数组中
    public static ChannelGroup channels=new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf in=(ByteBuf) msg;
        System.out.println("接收到客户端的消息"+in.toString(CharsetUtil.UTF_8));
        //写入并发送消息给客户端
//        while (true){
//            ctx.channel().writeAndFlush(Unpooled.copiedBuffer("你好，我是服务端，我已经收到你发的消息...", CharsetUtil.UTF_8));
//        }
        ctx.channel().writeAndFlush(Unpooled.copiedBuffer("你好，我是服务端，我已经收到你发的消息...", CharsetUtil.UTF_8));

    }

    /**
     *  处理 io事件的异常
     *
     * @param ctx
     * @param cause
     * @throws Exception 抛出异常
     *
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        // 连接断开时触发的动作
        Channel incoming = ctx.channel();
        System.out.println("客户端："+incoming.remoteAddress()+"已经断开");
        channels.remove(incoming);

    }
}
